"""
股票分析应用主文件
重构后的模块化架构
"""
from flask import Flask
from flask_cors import CORS
from config import Config

# 导入路由蓝图
from routes.stock_routes import stock_bp
from routes.system_routes import system_bp

# 创建Flask应用
app = Flask(__name__)
CORS(app)

# 配置应用
app.config['COMPRESS_REGISTER'] = False
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
app.config['SECRET_KEY'] = Config.SECRET_KEY

# 注册蓝图
app.register_blueprint(stock_bp)
app.register_blueprint(system_bp)

def retry_yfinance_call(func, max_retries=3, delay=1):
    """重试yfinance调用，处理429错误"""
    for attempt in range(max_retries):
        try:
            result = func()
            return result
        except Exception as e:
            if "429" in str(e) and attempt < max_retries - 1:
                # 指数退避 + 随机延迟
                sleep_time = delay * (2 ** attempt) + random.uniform(0, 1)
                print(f"遇到429错误，{sleep_time:.1f}秒后重试 (尝试 {attempt + 1}/{max_retries})")
                time.sleep(sleep_time)
            else:
                # 重新抛出异常，让上层处理
                raise e
    return None

@app.route('/api/stock/<symbol>', methods=['GET'])
def get_stock_info(symbol):
    """获取股票基本信息"""
    try:
        def get_stock_data():
            stock = yf.Ticker(symbol)
            return stock.info

        info = retry_yfinance_call(get_stock_data)
        if info is None:
            return jsonify({'error': 'Failed to fetch stock data after multiple retries'}), 500

        # 提取关键信息
        result = {
            'symbol': symbol,
            'name': info.get('longName', ''),
            'current_price': info.get('currentPrice', 0),
            'previous_close': info.get('previousClose', 0),
            'open': info.get('open', 0),
            'day_high': info.get('dayHigh', 0),
            'day_low': info.get('dayLow', 0),
            'volume': info.get('volume', 0),
            'market_cap': info.get('marketCap', 0),
            'currency': info.get('currency', 'USD'),
            'last_updated': datetime.now().isoformat()
        }

        return jsonify(result)
    except Exception as e:
        error_msg = str(e)
        print(f"Error in get_stock_info: {error_msg}")

        # 检查是否为429错误
        if "429" in error_msg:
            return jsonify({
                'error': 'API rate limit exceeded',
                'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
                'error_code': 'RATE_LIMIT_EXCEEDED',
                'retry_after': 'a few minutes'
            }), 429
        else:
            return jsonify({
                'error': 'Failed to fetch stock data',
                'details': error_msg
            }), 500

@app.route('/api/stock/<symbol>/financials', methods=['GET'])
def get_financial_metrics(symbol):
    """获取财务指标"""
    try:
        def get_financial_data():
            stock = yf.Ticker(symbol)
            return stock.info

        info = retry_yfinance_call(get_financial_data)
        if info is None:
            return jsonify({'error': 'Failed to fetch financial data after multiple retries'}), 500

        # 计算核心财务指标
        result = {
            'symbol': symbol,
            'pe_ratio': info.get('trailingPE', 0),  # 市盈率
            'pb_ratio': info.get('priceToBook', 0),  # 市净率
            'roe': info.get('returnOnEquity', 0),  # 净资产收益率
            'dividend_yield': info.get('dividendYield', 0),  # 股息率
            'eps': info.get('trailingEps', 0),  # 每股收益
            'revenue': info.get('totalRevenue', 0),  # 营业收入
            'debt_to_equity': info.get('debtToEquity', 0),  # 负债权益比
            'profit_margin': info.get('profitMargins', 0),  # 利润率
            'operating_margin': info.get('operatingMargins', 0),  # 营业利润率
            'last_updated': datetime.now().isoformat()
        }

        return jsonify(result)
    except Exception as e:
        error_msg = str(e)
        print(f"Error in get_financial_metrics: {error_msg}")

        # 检查是否为429错误
        if "429" in error_msg:
            return jsonify({
                'error': 'API rate limit exceeded',
                'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
                'error_code': 'RATE_LIMIT_EXCEEDED',
                'retry_after': 'a few minutes'
            }), 429
        else:
            return jsonify({
                'error': 'Failed to fetch financial data',
                'details': error_msg
            }), 500

@app.route('/api/stock/<symbol>/risk', methods=['GET'])
def get_risk_analysis(symbol):
    """获取风险评估"""
    try:
        # 获取一年历史数据
        end_date = datetime.now()
        start_date = end_date - timedelta(days=365)

        def get_historical_data():
            return yf.download(symbol, start=start_date, end=end_date, auto_adjust=False)

        stock_data = retry_yfinance_call(get_historical_data)
        if stock_data is None:
            return jsonify({'error': 'Failed to fetch historical data after multiple retries'}), 500

        if stock_data.empty:
            return jsonify({'error': 'No data available'}), 404

        # 计算日收益率
        stock_data['Daily_Return'] = stock_data['Close'].pct_change()

        # 计算风险指标
        volatility = float(stock_data['Daily_Return'].std()) * np.sqrt(252)  # 年化波动率

        # 计算最大回撤
        rolling_max = stock_data['Close'].expanding().max()
        drawdown = (stock_data['Close'] - rolling_max) / rolling_max
        max_drawdown = float(drawdown.min())

        # 计算Sharpe比率 (假设无风险利率为2%)
        risk_free_rate = 0.02
        annual_return = (float(stock_data['Close'].iloc[-1]) / float(stock_data['Close'].iloc[0])) ** (252/len(stock_data)) - 1
        sharpe_ratio = (annual_return - risk_free_rate) / volatility if volatility != 0 else 0

        result = {
            'symbol': symbol,
            'volatility': round(volatility * 100, 2),  # 百分比
            'max_drawdown': round(max_drawdown * 100, 2),  # 百分比
            'sharpe_ratio': round(float(sharpe_ratio), 3),
            'beta': 1.0,  # 默认值，需要市场数据计算
            'var_95': round(float(stock_data['Daily_Return'].quantile(0.05)) * 100, 2),  # 95% VaR
            'current_price': round(float(stock_data['Close'].iloc[-1]), 2),
            'year_high': round(float(stock_data['High'].max()), 2),
            'year_low': round(float(stock_data['Low'].min()), 2),
            'last_updated': datetime.now().isoformat()
        }

        return jsonify(result)
    except Exception as e:
        error_msg = str(e)
        print(f"Error in get_risk_analysis: {error_msg}")

        # 检查是否为429错误
        if "429" in error_msg:
            return jsonify({
                'error': 'API rate limit exceeded',
                'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
                'error_code': 'RATE_LIMIT_EXCEEDED',
                'retry_after': 'a few minutes'
            }), 429
        else:
            return jsonify({
                'error': 'Failed to calculate risk metrics',
                'details': error_msg
            }), 500

@app.route('/api/stock/<symbol>/chart', methods=['GET'])
def get_chart_data(symbol):
    """获取图表数据"""
    try:
        # 获取一年历史数据
        end_date = datetime.now()
        start_date = end_date - timedelta(days=365)

        stock_data = yf.download(symbol, start=start_date, end=end_date, auto_adjust=False)

        if stock_data.empty:
            return jsonify({'error': 'No data available'}), 404

        # 准备图表数据
        chart_data = []
        for i in range(len(stock_data)):
            chart_data.append({
                'date': stock_data.index[i].strftime('%Y-%m-%d'),
                'open': round(float(stock_data['Open'].iloc[i]), 2),
                'high': round(float(stock_data['High'].iloc[i]), 2),
                'low': round(float(stock_data['Low'].iloc[i]), 2),
                'close': round(float(stock_data['Close'].iloc[i]), 2),
                'volume': int(stock_data['Volume'].iloc[i])
            })

        # 计算移动平均线
        stock_data['MA20'] = stock_data['Close'].rolling(window=20).mean()
        stock_data['MA50'] = stock_data['Close'].rolling(window=50).mean()

        ma_data = []
        for i in range(len(stock_data)):
            ma20_val = stock_data['MA20'].iloc[i]
            ma50_val = stock_data['MA50'].iloc[i]
            if pd.notna(ma20_val) and pd.notna(ma50_val):
                ma_data.append({
                    'date': stock_data.index[i].strftime('%Y-%m-%d'),
                    'ma20': round(float(ma20_val), 2),
                    'ma50': round(float(ma50_val), 2)
                })

        result = {
            'symbol': symbol,
            'price_data': chart_data,
            'ma_data': ma_data,
            'last_updated': datetime.now().isoformat()
        }

        return jsonify(result)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/stock/<symbol>/recommendation', methods=['GET'])
def get_investment_recommendation(symbol):
    """获取投资建议"""
    try:
        def get_recommendation_data():
            # 获取财务和风险数据
            stock = yf.Ticker(symbol)
            info = stock.info

            # 获取风险分析
            end_date = datetime.now()
            start_date = end_date - timedelta(days=365)
            stock_data = yf.download(symbol, start=start_date, end=end_date, auto_adjust=False)

            return info, stock_data

        info, stock_data = retry_yfinance_call(get_recommendation_data)
        if info is None or stock_data is None:
            return jsonify({'error': 'Failed to fetch data after multiple retries'}), 500

        if stock_data.empty:
            return jsonify({'error': 'No data available'}), 404

        # 安全地获取和计算指标
        def safe_float(value, default=0):
            """安全地将值转换为浮点数"""
            if value is None:
                return default
            try:
                return float(value)
            except (ValueError, TypeError):
                return default

        # 计算指标
        pe_ratio = safe_float(info.get('trailingPE'))
        pb_ratio = safe_float(info.get('priceToBook'))
        roe = safe_float(info.get('returnOnEquity'))
        dividend_yield = safe_float(info.get('dividendYield'))

        stock_data = stock_data.copy()  # 避免SettingWithCopyWarning
        stock_data['Daily_Return'] = stock_data['Close'].pct_change()

        # 计算波动率，确保数据有效
        if len(stock_data['Daily_Return'].dropna()) > 1:
            volatility = safe_float(stock_data['Daily_Return'].std() * np.sqrt(252))
        else:
            volatility = 0

        # 简单的投资建议逻辑
        signals = []
        score = 0

        # PE比率评估
        if pe_ratio > 0:
            if pe_ratio < 15:
                signals.append("PE比率较低，可能被低估")
                score += 2
            elif pe_ratio > 30:
                signals.append("PE比率较高，可能被高估")
                score -= 1

        # ROE评估
        if roe > 0:
            if roe > 0.15:
                signals.append("ROE优秀，盈利能力强")
                score += 2
            elif roe < 0.05:
                signals.append("ROE较低，盈利能力弱")
                score -= 1

        # 股息率评估
        if dividend_yield > 0:
            if dividend_yield > 0.03:
                signals.append("股息率较高，有稳定现金流")
                score += 1

        # 波动率评估
        if volatility < 0.2:
            signals.append("波动率较低，风险相对较小")
            score += 1
        elif volatility > 0.4:
            signals.append("波动率较高，风险较大")
            score -= 1

        # 综合建议
        if score >= 3:
            recommendation = "买入"
            confidence = "高"
        elif score >= 1:
            recommendation = "持有"
            confidence = "中等"
        elif score >= -1:
            recommendation = "观望"
            confidence = "中等"
        else:
            recommendation = "卖出"
            confidence = "高"

        result = {
            'symbol': symbol,
            'recommendation': recommendation,
            'confidence': confidence,
            'score': score,
            'signals': signals,
            'warning': "投资有风险，建议结合个人风险承受能力做出决策",
            'last_updated': datetime.now().isoformat()
        }

        return jsonify(result)
    except Exception as e:
        error_msg = str(e)
        print(f"Error in get_investment_recommendation: {error_msg}")

        # 检查是否为429错误
        if "429" in error_msg:
            return jsonify({
                'error': 'API rate limit exceeded',
                'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
                'error_code': 'RATE_LIMIT_EXCEEDED',
                'retry_after': 'a few minutes'
            }), 429
        else:
            return jsonify({
                'error': 'Failed to generate investment recommendation',
                'details': error_msg
            }), 500

@app.route('/api/stock/<symbol>/ai-analysis', methods=['POST'])
def get_ai_analysis(symbol):
    """获取AI投资分析"""
    try:
        # 获取股票数据
        stock = yf.Ticker(symbol)
        info = stock.info

        # 获取历史数据用于计算技术指标
        end_date = datetime.now()
        start_date = end_date - timedelta(days=365)
        stock_data = yf.download(symbol, start=start_date, end=end_date, auto_adjust=False)

        # 构建分析数据 - 安全地处理所有数据
        def safe_get(value, default=0):
            """安全地获取数值，避免Series问题"""
            if value is None:
                return default
            try:
                if hasattr(value, 'iloc'):
                    return float(value.iloc[0]) if len(value) > 0 else default
                return float(value)
            except (ValueError, TypeError, AttributeError):
                return default

        def safe_get_str(value, default=''):
            """安全地获取字符串"""
            if value is None:
                return default
            try:
                if hasattr(value, 'iloc'):
                    return str(value.iloc[0]) if len(value) > 0 else default
                return str(value)
            except (ValueError, TypeError, AttributeError):
                return default

        analysis_data = {
            'symbol': safe_get_str(symbol),
            'company_name': safe_get_str(info.get('longName', '')),
            'current_price': safe_get(info.get('currentPrice')),
            'previous_close': safe_get(info.get('previousClose')),
            'day_change': round(((safe_get(info.get('currentPrice')) - safe_get(info.get('previousClose'))) / max(safe_get(info.get('previousClose')), 1)) * 100, 2),
            'volume': safe_get(info.get('volume')),
            'market_cap': safe_get(info.get('marketCap')),
            'pe_ratio': safe_get(info.get('trailingPE')),
            'pb_ratio': safe_get(info.get('priceToBook')),
            'roe': safe_get(info.get('returnOnEquity')),
            'dividend_yield': safe_get(info.get('dividendYield')),
            'eps': safe_get(info.get('trailingEps')),
            'revenue': safe_get(info.get('totalRevenue')),
            'debt_to_equity': safe_get(info.get('debtToEquity')),
            'profit_margin': safe_get(info.get('profitMargins')),
            'operating_margin': safe_get(info.get('operatingMargins')),
            'sector': safe_get_str(info.get('sector', '')),
            'industry': safe_get_str(info.get('industry', '')),
            'business_summary': safe_get_str(info.get('longBusinessSummary', '')),
            '52_week_high': safe_get(info.get('fiftyTwoWeekHigh')),
            '52_week_low': safe_get(info.get('fiftyTwoWeekLow')),
            'analyst_rating': safe_get_str(info.get('recommendationKey', '')),
            'target_price': safe_get(info.get('targetMeanPrice')),
        }

        # 添加技术指标
        if not stock_data.empty:
            try:
                stock_data = stock_data.copy()  # 避免SettingWithCopyWarning
                stock_data['Daily_Return'] = stock_data['Close'].pct_change()
                daily_return_std = stock_data['Daily_Return'].std()
                volatility = float(daily_return_std) * np.sqrt(252)

                # 计算20日和50日移动平均线
                stock_data['MA20'] = stock_data['Close'].rolling(window=20).mean()
                stock_data['MA50'] = stock_data['Close'].rolling(window=50).mean()

                # Use .item() to avoid FutureWarning about float on single element Series
                close_last = stock_data['Close'].iloc[-1]
                current_price = float(close_last.item() if hasattr(close_last, 'item') else close_last)
                ma20_val = stock_data['MA20'].iloc[-1]
                ma50_val = stock_data['MA50'].iloc[-1]
                ma20 = float(ma20_val) if pd.notna(ma20_val) else 0
                ma50 = float(ma50_val) if pd.notna(ma50_val) else 0

                # 计算RSI (14日)
                delta = stock_data['Close'].diff()
                gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
                loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()

                # 安全地计算RSI
                try:
                    # 避免除零错误和Series模糊性错误
                    with np.errstate(divide='ignore', invalid='ignore'):
                        rs_val = gain / loss
                        # 将无穷大和NaN替换为安全的值
                        rs_val = rs_val.replace([np.inf, -np.inf], np.nan).fillna(1)

                    rsi_val = rs_val.iloc[-1] if pd.notna(rs_val.iloc[-1]) else 1
                    rsi = float(100 - (100 / (1 + rsi_val)))
                except Exception as e:
                    print(f"RSI calculation handled: {e}")
                    rsi = 50  # 默认中性值

                analysis_data.update({
                    'volatility': round(volatility * 100, 2),
                    'current_price_tech': current_price,
                    'ma20': round(ma20, 2),
                    'ma50': round(ma50, 2),
                    'rsi': round(rsi, 2),
                    'price_vs_ma20': round(((current_price - ma20) / ma20) * 100, 2) if ma20 > 0 else 0,
                    'price_vs_ma50': round(((current_price - ma50) / ma50) * 100, 2) if ma50 > 0 else 0,
                })
            except Exception as e:
                print(f"技术指标计算错误: {e}")
                # 如果技术指标计算失败，设置默认值
                analysis_data.update({
                    'volatility': 0,
                    'current_price_tech': analysis_data.get('current_price', 0),
                    'ma20': 0,
                    'ma50': 0,
                    'rsi': 50,
                    'price_vs_ma20': 0,
                    'price_vs_ma50': 0,
                })

        # 构建AI分析提示词
        prompt = build_ai_analysis_prompt(analysis_data)

        # 调用真实的AI API
        ai_response = call_ai_api(prompt)

        return jsonify({
            'prompt': prompt,
            'ai_analysis': ai_response,
            'analysis_data': analysis_data,
            'timestamp': datetime.now().isoformat()
        })

    except Exception as e:
        error_msg = str(e)
        print(f"Error in get_ai_analysis: {error_msg}")

        # 检查是否有error_code属性（自定义异常）
        if hasattr(e, 'error_code'):
            return jsonify({
                'error': error_msg,
                'details': error_msg,
                'error_code': e.error_code
            }), 500

        # 检查是否为429错误
        if "429" in error_msg:
            return jsonify({
                'error': 'API rate limit exceeded',
                'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
                'error_code': 'RATE_LIMIT_EXCEEDED',
                'retry_after': 'a few minutes'
            }), 429
        else:
            return jsonify({
                'error': 'Failed to generate AI analysis',
                'details': error_msg,
                'error_code': 'AI_ANALYSIS_ERROR'
            }), 500

def build_ai_analysis_prompt(data):
    """构建AI投资分析的提示词"""
    # 安全地获取所有数值
    symbol = str(data.get('symbol', ''))
    company_name = str(data.get('company_name', ''))
    industry = str(data.get('industry', ''))
    sector = str(data.get('sector', ''))
    current_price = float(data.get('current_price', 0)) if data.get('current_price') is not None else 0
    day_change = float(data.get('day_change', 0)) if data.get('day_change') is not None else 0
    week52_high = float(data.get('52_week_high', 0)) if data.get('52_week_high') is not None else 0
    week52_low = float(data.get('52_week_low', 0)) if data.get('52_week_low') is not None else 0
    pe_ratio = float(data.get('pe_ratio', 0)) if data.get('pe_ratio') is not None else 0
    pb_ratio = float(data.get('pb_ratio', 0)) if data.get('pb_ratio') is not None else 0
    roe = float(data.get('roe', 0)) if data.get('roe') is not None else 0
    dividend_yield = float(data.get('dividend_yield', 0)) if data.get('dividend_yield') is not None else 0
    eps = float(data.get('eps', 0)) if data.get('eps') is not None else 0
    revenue = float(data.get('revenue', 0)) if data.get('revenue') is not None else 0
    debt_to_equity = float(data.get('debt_to_equity', 0)) if data.get('debt_to_equity') is not None else 0
    profit_margin = float(data.get('profit_margin', 0)) if data.get('profit_margin') is not None else 0
    operating_margin = float(data.get('operating_margin', 0)) if data.get('operating_margin') is not None else 0
    volatility = data.get('volatility', 'N/A')
    ma20 = float(data.get('ma20', 0)) if data.get('ma20') is not None else 0
    ma50 = float(data.get('ma50', 0)) if data.get('ma50') is not None else 0
    rsi = data.get('rsi', 'N/A')
    price_vs_ma20 = float(data.get('price_vs_ma20', 0)) if data.get('price_vs_ma20') is not None else 0
    price_vs_ma50 = float(data.get('price_vs_ma50', 0)) if data.get('price_vs_ma50') is not None else 0
    analyst_rating = str(data.get('analyst_rating', ''))
    target_price = float(data.get('target_price', 0)) if data.get('target_price') is not None else 0
    business_summary = str(data.get('business_summary', ''))[:500]

    prompt = f"""你是一位专业的股票投资分析师，请对以下股票进行全面的投資分析：

## 股票基本信息
- 股票代码: {symbol}
- 公司名称: {company_name}
- 所属行业: {industry}
- 所属板块: {sector}
- 当前股价: ${current_price:.2f}
- 日涨跌幅: {day_change:.2f}%
- 52周最高: ${week52_high:.2f}
- 52周最低: ${week52_low:.2f}

## 财务指标
- 市盈率(PE): {pe_ratio:.2f}
- 市净率(PB): {pb_ratio:.2f}
- 净资产收益率(ROE): {roe:.2%}
- 股息率: {dividend_yield:.2%}
- 每股收益(EPS): ${eps:.2f}
- 营业收入: ${revenue:,.0f}
- 负债权益比: {debt_to_equity:.2f}
- 利润率: {profit_margin:.2%}
- 营业利润率: {operating_margin:.2%}

## 技术指标
- 年化波动率: {volatility}%
- 20日移动平均线: ${ma20:.2f}
- 50日移动平均线: ${ma50:.2f}
- 相对强弱指数(RSI): {rsi}
- 股价相对20日均线的偏离: {price_vs_ma20:.2f}%
- 股价相对50日均线的偏离: {price_vs_ma50:.2f}%

## 市场观点
- 分析师评级: {analyst_rating}
- 目标价: ${target_price:.2f}

## 公司业务简介
{business_summary}...

请基于以上信息，从以下几个维度进行专业分析：

1. **估值分析**: 评估当前估值水平是否合理
2. **财务健康度**: 分析公司的财务状况和盈利能力
3. **技术面分析**: 基于技术指标判断短期走势
4. **行业前景**: 分析行业发展趋势和公司竞争力
5. **风险评估**: 指出主要风险因素
6. **投资建议**: 给出明确的投资建议（买入/持有/卖出）和理由

请用中文回答，分析要专业、客观、有理有据。"""
    return prompt

def call_ai_api(prompt, max_retries=3):
    """调用OpenAI兼容的AI接口"""
    if not AI_API_KEY:
        # 创建一个自定义异常类来携带错误信息
        class APIKeyError(Exception):
            def __init__(self, message, error_code):
                super().__init__(message)
                self.error_code = error_code

        raise APIKeyError("AI_API_KEY 未配置，请检查环境变量", "API_KEY_MISSING")

    headers = {
        'Authorization': f'Bearer {AI_API_KEY}',
        'Content-Type': 'application/json',
    }

    data = {
        'model': AI_MODEL,
        'messages': [
            {
                'role': 'system',
                'content': '你是一位专业的股票投资分析师，具有丰富的财务分析经验和市场洞察力。请基于提供的数据进行客观、专业的分析。'
            },
            {
                'role': 'user',
                'content': prompt
            }
        ],
        'temperature': 0.7,
        'max_tokens': 2000,
    }

    for attempt in range(max_retries):
        try:
            response = requests.post(
                f'{AI_API_BASE_URL}/chat/completions',
                headers=headers,
                json=data,
                timeout=30
            )

            if response.status_code == 200:
                result = response.json()
                return result['choices'][0]['message']['content']
            elif response.status_code == 429:
                if attempt < max_retries - 1:
                    sleep_time = (2 ** attempt) + random.uniform(0, 1)
                    print(f"AI API限流，{sleep_time:.1f}秒后重试 (尝试 {attempt + 1}/{max_retries})")
                    time.sleep(sleep_time)
                    continue
                else:
                    raise Exception(f"AI API rate limit exceeded after {max_retries} retries")
            else:
                error_info = response.json() if response.headers.get('content-type', '').startswith('application/json') else response.text
                raise Exception(f"AI API调用失败 ({response.status_code}): {error_info}")

        except requests.exceptions.RequestException as e:
            if attempt < max_retries - 1:
                print(f"AI API请求错误，重试中: {str(e)}")
                time.sleep(1)
                continue
            else:
                raise Exception(f"AI API请求失败: {str(e)}")

    raise Exception("AI API调用失败：未知错误")

@app.route('/api/stock/<symbol>/ai-analysis-stream', methods=['POST'])
def get_ai_analysis_stream(symbol):
    """获取AI投资分析 - 流式响应"""
    try:
        # 获取请求数据
        data = request.get_json()
        question = data.get('question', '')
        analysis_type = data.get('analysis_type', 'comprehensive')  # 添加分析类型
        conversation_history = data.get('conversation_history', [])

        if not question.strip():
            return jsonify({'error': 'Question is required'}), 400

        # 获取股票数据
        def get_analysis_data():
            stock = yf.Ticker(symbol)
            info = stock.info
            # 获取历史数据用于计算技术指标
            end_date = datetime.now()
            start_date = end_date - timedelta(days=365)
            stock_data = yf.download(symbol, start=start_date, end=end_date, auto_adjust=False)
            return info, stock_data

        info, stock_data = retry_yfinance_call(get_analysis_data)
        if info is None or stock_data is None:
            return jsonify({'error': 'Failed to fetch data after multiple retries'}), 500

        # 计算技术分析指标
        def calculate_technical_indicators(stock_data):
            """计算技术分析指标"""
            if stock_data is None or len(stock_data) == 0:
                return {}

            # 提取价格数据（处理多级列名）
            if len(stock_data.columns) > 0 and isinstance(stock_data.columns[0], tuple):
                ticker = stock_data.columns[0][1]  # 获取股票代码，如 'AAPL'
                close_prices = stock_data[('Close', ticker)].dropna()
                volumes = stock_data[('Volume', ticker)].dropna()
                high_prices = stock_data[('High', ticker)].dropna()
                low_prices = stock_data[('Low', ticker)].dropna()
            else:
                # 如果是普通列名
                close_prices = stock_data['Close'].dropna()
                volumes = stock_data['Volume'].dropna()
                high_prices = stock_data['High'].dropna()
                low_prices = stock_data['Low'].dropna()

            if len(close_prices) < 20:  # 至少需要20天的数据
                return {}

            try:
                import numpy as np

                # 基本统计
                current_price = close_prices.iloc[-1]
                price_20d = close_prices.iloc[-20:].mean()
                price_50d = close_prices.iloc[-50:].mean() if len(close_prices) >= 50 else None
                price_200d = close_prices.iloc[-200:].mean() if len(close_prices) >= 200 else None

                # 波动率计算（20日标准差）
                returns = close_prices.pct_change().dropna()
                volatility_20d = returns.iloc[-20:].std() * np.sqrt(252) if len(returns) >= 20 else None

                # RSI计算（14日）
                def calculate_rsi(prices, period=14):
                    delta = prices.diff()
                    gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
                    loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
                    rs = gain / loss
                    return 100 - (100 / (1 + rs))

                rsi = calculate_rsi(close_prices)
                current_rsi = rsi.iloc[-1] if len(rsi) > 0 else None

                # MACD计算
                def calculate_macd(prices, fast=12, slow=26, signal=9):
                    exp1 = prices.ewm(span=fast).mean()
                    exp2 = prices.ewm(span=slow).mean()
                    macd = exp1 - exp2
                    signal = macd.ewm(span=signal).mean()
                    return macd, signal

                macd, signal = calculate_macd(close_prices)
                current_macd = macd.iloc[-1] if len(macd) > 0 else None
                current_signal = signal.iloc[-1] if len(signal) > 0 else None
                macd_histogram = current_macd - current_signal if (current_macd is not None and current_signal is not None) else None

                # 布林带计算（20日）
                sma_20 = close_prices.rolling(window=20).mean()
                std_20 = close_prices.rolling(window=20).std()
                upper_band = sma_20 + (std_20 * 2)
                lower_band = sma_20 - (std_20 * 2)
                current_upper = upper_band.iloc[-1] if len(upper_band) > 0 else None
                current_lower = lower_band.iloc[-1] if len(lower_band) > 0 else None
                current_sma = sma_20.iloc[-1] if len(sma_20) > 0 else None

                # 价格相对位置（布林带）
                bb_position = ((current_price - current_lower) / (current_upper - current_lower)) * 100 if (current_upper and current_lower and current_upper > current_lower) else None

                # 支撑位和阻力位（最近3个月的最低/最高）
                recent_high = high_prices.iloc[-63:].max() if len(high_prices) >= 63 else high_prices.max()
                recent_low = low_prices.iloc[-63:].min() if len(low_prices) >= 63 else low_prices.min()

                # 成交量分析
                avg_volume = volumes.iloc[-20:].mean() if len(volumes) >= 20 else None
                current_volume = volumes.iloc[-1] if len(volumes) > 0 else None
                volume_ratio = current_volume / avg_volume if (current_volume and avg_volume and avg_volume > 0) else None

                # 价格动量（1个月、3个月）
                momentum_1m = ((current_price / close_prices.iloc[-22]) - 1) * 100 if len(close_prices) >= 22 else None
                momentum_3m = ((current_price / close_prices.iloc[-63]) - 1) * 100 if len(close_prices) >= 63 else None

                # 趋势判断（基于移动平均线）
                trend_signal = "NEUTRAL"
                if price_20d is not None and price_50d is not None:
                    if current_price > price_20d and price_20d > price_50d:
                        trend_signal = "BULLISH"
                    elif current_price < price_20d and price_20d < price_50d:
                        trend_signal = "BEARISH"

                # RSI信号
                rsi_signal = "NEUTRAL"
                if current_rsi is not None:
                    if current_rsi > 70:
                        rsi_signal = "OVERBOUGHT"
                    elif current_rsi < 30:
                        rsi_signal = "OVERSOLD"

                return {
                    'current_price': current_price,
                    'sma_20d': price_20d,
                    'sma_50d': price_50d,
                    'sma_200d': price_200d,
                    'volatility_20d': volatility_20d,
                    'rsi': current_rsi,
                    'rsi_signal': rsi_signal,
                    'macd': current_macd,
                    'macd_signal': current_signal,
                    'macd_histogram': macd_histogram,
                    'bb_upper': current_upper,
                    'bb_lower': current_lower,
                    'bb_sma': current_sma,
                    'bb_position': bb_position,
                    'recent_high': recent_high,
                    'recent_low': recent_low,
                    'avg_volume_20d': avg_volume,
                    'current_volume': current_volume,
                    'volume_ratio': volume_ratio,
                    'momentum_1m': momentum_1m,
                    'momentum_3m': momentum_3m,
                    'trend_signal': trend_signal,
                    'rsi_overbought_oversold': rsi_signal
                }
            except Exception as e:
                print(f"Error calculating technical indicators: {e}")
                return {}

        # 构建分析数据（复用现有逻辑）
        def safe_get(value, default=0):
            """安全地获取数值，避免Series问题"""
            if value is None:
                return default
            try:
                if hasattr(value, 'iloc'):
                    return float(value.iloc[0]) if len(value) > 0 else default
                return float(value)
            except (ValueError, TypeError, AttributeError):
                return default

        def safe_get_str(value, default=''):
            """安全地获取字符串"""
            if value is None:
                return default
            try:
                if hasattr(value, 'iloc'):
                    return str(value.iloc[0]) if len(value) > 0 else default
                return str(value)
            except (ValueError, TypeError, AttributeError):
                return default

        analysis_data = {
            'symbol': safe_get_str(symbol),
            'company_name': safe_get_str(info.get('longName', '')),
            'current_price': safe_get(info.get('currentPrice')),
            'previous_close': safe_get(info.get('previousClose')),
            'day_change': round(((safe_get(info.get('currentPrice')) - safe_get(info.get('previousClose'))) / max(safe_get(info.get('previousClose')), 1)) * 100, 2),
            'day_high': safe_get(info.get('dayHigh')),
            'day_low': safe_get(info.get('dayLow')),
            'volume': safe_get(info.get('volume')),
            'average_volume': safe_get(info.get('averageVolume')),
            'market_cap': safe_get(info.get('marketCap')),
            'enterprise_value': safe_get(info.get('enterpriseValue')),

            # 估值指标
            'pe_ratio': safe_get(info.get('trailingPE')),
            'forward_pe': safe_get(info.get('forwardPE')),
            'pb_ratio': safe_get(info.get('priceToBook')),
            'price_to_sales': safe_get(info.get('priceToSalesTrailing12Months')),
            'ev_to_revenue': safe_get(info.get('enterpriseToRevenue')),
            'ev_to_ebitda': safe_get(info.get('enterpriseToEbitda')),
            'peg_ratio': safe_get(info.get('trailingPegRatio')),

            # 盈利能力指标
            'roe': safe_get(info.get('returnOnEquity')),
            'roa': safe_get(info.get('returnOnAssets')),
            'profit_margins': safe_get(info.get('profitMargins')),
            'gross_margins': safe_get(info.get('grossMargins')),
            'operating_margins': safe_get(info.get('operatingMargins')),
            'ebitda_margins': safe_get(info.get('ebitdaMargins')),

            # 成长性指标
            'revenue_growth': safe_get(info.get('revenueGrowth')),
            'earnings_growth': safe_get(info.get('earningsGrowth')),
            'earnings_quarterly_growth': safe_get(info.get('earningsQuarterlyGrowth')),

            # 财务健康指标
            'dividend_yield': safe_get(info.get('dividendYield')),
            'dividend_rate': safe_get(info.get('dividendRate')),
            'payout_ratio': safe_get(info.get('payoutRatio')),
            'debt_to_equity': safe_get(info.get('debtToEquity')),
            'current_ratio': safe_get(info.get('currentRatio')),
            'quick_ratio': safe_get(info.get('quickRatio')),
            'beta': safe_get(info.get('beta')),

            # 现金流指标
            'free_cashflow': safe_get(info.get('freeCashflow')),
            'operating_cashflow': safe_get(info.get('operatingCashflow')),
            'total_cash': safe_get(info.get('totalCash')),
            'total_debt': safe_get(info.get('totalDebt')),

            # 股价技术指标
            '52_week_high': safe_get(info.get('fiftyTwoWeekHigh')),
            '52_week_low': safe_get(info.get('fiftyTwoWeekLow')),
            '50_day_average': safe_get(info.get('fiftyDayAverage')),
            '200_day_average': safe_get(info.get('twoHundredDayAverage')),

            # 分析师预期
            'target_mean_price': safe_get(info.get('targetMeanPrice')),
            'target_high_price': safe_get(info.get('targetHighPrice')),
            'target_low_price': safe_get(info.get('targetLowPrice')),
            'recommendation_mean': safe_get(info.get('recommendationMean')),
            'number_of_analysts': safe_get(info.get('numberOfAnalystOpinions')),

            # 公司基本信息
            'sector': safe_get_str(info.get('sector', '')),
            'industry': safe_get_str(info.get('industry', '')),
            'full_time_employees': safe_get(info.get('fullTimeEmployees')),
            'website': safe_get_str(info.get('website', '')),
            'business_summary': safe_get_str(info.get('longBusinessSummary', '')),

            # 其他重要指标
            'book_value': safe_get(info.get('bookValue')),
            'total_revenue': safe_get(info.get('totalRevenue')),
            'net_income': safe_get(info.get('netIncomeToCommon')),
            'trailing_eps': safe_get(info.get('trailingEps')),
            'forward_eps': safe_get(info.get('forwardEps')),
            'shares_outstanding': safe_get(info.get('sharesOutstanding')),
            'held_percent_institutions': safe_get(info.get('heldPercentInstitutions')),
            'held_percent_insiders': safe_get(info.get('heldPercentInsiders')),
            'short_percent_of_float': safe_get(info.get('shortPercentOfFloat')),

            # 风险指标
            'overall_risk': safe_get(info.get('overallRisk')),
            'audit_risk': safe_get(info.get('auditRisk')),
            'board_risk': safe_get(info.get('boardRisk')),
            'compensation_risk': safe_get(info.get('compensationRisk')),
            'share_holder_rights_risk': safe_get(info.get('shareHolderRightsRisk'))
        }

        # 添加技术指标数据
        technical_indicators = calculate_technical_indicators(stock_data)
        analysis_data.update(technical_indicators)

        # 添加用户问题和分析类型到分析数据中
        analysis_data['user_question'] = question
        analysis_data['analysis_type'] = analysis_type
        analysis_data['conversation_history'] = conversation_history

        # 构建AI分析提示词（根据分析类型和用户问题）
        prompt = build_specialized_analysis_prompt(analysis_data)

        # 流式调用AI API
        def generate():
            try:
                if not AI_API_KEY:
                    yield f"data: {json.dumps({'error': 'AI_API_KEY 未配置'})}\n\n".encode('utf-8')
                    yield f"data: [DONE]\n\n".encode('utf-8')
                    return

                headers = {
                    'Authorization': f'Bearer {AI_API_KEY}',
                    'Content-Type': 'application/json',
                }

                # 构建对话消息（包含历史对话）
                messages = [
                    {
                        'role': 'system',
                        'content': '你是一位专业的股票投资分析师，具有丰富的财务分析经验和市场洞察力。请基于提供的数据进行客观、专业的分析。回答要简洁明了，使用markdown格式，包含适当的标题、列表和重点标记。'
                    }
                ]

                # 添加对话历史（限制最近几条）
                for msg in conversation_history[-4:]:  # 只保留最近4条对话
                    if msg.get('role') and msg.get('content'):
                        messages.append({
                            'role': msg['role'],
                            'content': msg['content']
                        })

                # 添加当前问题
                messages.append({
                    'role': 'user',
                    'content': prompt
                })

                data = {
                    'model': AI_MODEL,
                    'messages': messages,
                    'temperature': 0.7,
                    'max_tokens': 2000,
                    'stream': True  # 启用流式响应
                }

                # 发送流式请求
                response = requests.post(
                    f'{AI_API_BASE_URL}/chat/completions',
                    headers=headers,
                    json=data,
                    stream=True,
                    timeout=30
                )

                if response.status_code == 200:
                    for line in response.iter_lines():
                        if line:
                            line_str = line.decode('utf-8')
                            if line_str.startswith('data: '):
                                data_str = line_str[6:]
                                if data_str == '[DONE]':
                                    yield f"data: [DONE]\n\n".encode('utf-8')
                                    break
                                try:
                                    data_json = json.loads(data_str)
                                    if 'choices' in data_json and len(data_json['choices']) > 0:
                                        delta = data_json['choices'][0].get('delta', {})
                                        if 'content' in delta:
                                            content = delta['content']
                                            yield f"data: {json.dumps({'content': content})}\n\n".encode('utf-8')
                                except json.JSONDecodeError:
                                    continue
                else:
                    error_msg = f"AI API error: {response.status_code}"
                    yield f"data: {json.dumps({'error': error_msg})}\n\n".encode('utf-8')
                    yield f"data: [DONE]\n\n".encode('utf-8')

            except Exception as e:
                error_msg = str(e)
                yield f"data: {json.dumps({'error': f'Streaming error: {error_msg}'})}\n\n".encode('utf-8')
                yield f"data: [DONE]\n\n".encode('utf-8')

        return Response(
            generate(),
            mimetype='text/event-stream',
            headers={
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0',
                'Connection': 'keep-alive',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Headers': 'Cache-Control, Content-Type',
                'X-Accel-Buffering': 'no',  # 禁用Nginx缓冲
                'X-Content-Type-Options': 'nosniff',
                'Content-Encoding': 'identity',  # 强制不压缩
                'Transfer-Encoding': 'chunked'   # 明确指定分块传输
            },
            direct_passthrough=True  # 禁用Flask缓冲
        )

    except Exception as e:
        error_msg = str(e)
        print(f"Error in get_ai_analysis_stream: {error_msg}")
        return jsonify({
            'error': 'Failed to start AI analysis stream',
            'details': error_msg
        }), 500


@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查"""
    ai_configured = bool(AI_API_KEY)
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat(),
        'version': '1.0.0',
        'ai_configured': ai_configured,
        'ai_model': AI_MODEL if ai_configured else None
    })


@app.route('/api/ai-status', methods=['GET'])
def ai_status():
    """AI服务状态检查"""
    return jsonify({
        'api_key_configured': bool(AI_API_KEY),
        'api_base_url': AI_API_BASE_URL,
        'model': AI_MODEL,
        'model_provider': 'OpenAI Compatible API'
    })

def build_specialized_analysis_prompt(data):
    """根据分析类型构建专门化的AI分析提示词"""
    symbol = data.get('symbol', '未知股票')
    company_name = data.get('company_name', '未知公司')
    analysis_type = data.get('analysis_type', 'comprehensive')
    user_question = data.get('user_question', '')

    # 格式化市值显示
    def format_market_cap(market_cap):
        if not market_cap or market_cap == 0:
            return 'N/A'
        if market_cap > 1e12:
            return f"${market_cap/1e12:.1f}万亿"
        elif market_cap > 1e9:
            return f"${market_cap/1e9:.1f}亿"
        elif market_cap > 1e6:
            return f"${market_cap/1e6:.1f}百万"
        else:
            return f"${market_cap:,.0f}"

    def format_percentage(value):
        if not value or value == 0:
            return 'N/A'
        return f"{value*100:.2f}%" if abs(value) < 1 else f"{value:.1f}%"

    def format_currency(value):
        if not value or value == 0:
            return 'N/A'
        if value > 1e9:
            return f"${value/1e9:.1f}亿"
        elif value > 1e6:
            return f"${value/1e6:.1f}百万"
        else:
            return f"${value:,.2f}"

    # 基础股票信息
    stock_info = f"""**📊 股票基础信息**
- **股票代码**: {symbol}
- **公司名称**: {company_name}
- **当前价格**: ${data.get('current_price', 'N/A')}
- **今日涨跌幅**: {data.get('day_change', 'N/A')}%
- **52周区间**: ${data.get('52_week_low', 'N/A')} - ${data.get('52_week_high', 'N/A')}
- **市值**: {format_market_cap(data.get('market_cap'))}
- **行业**: {data.get('sector', 'N/A')} / {data.get('industry', 'N/A')}

**💰 估值指标**
- **PE比率(TTM)**: {data.get('pe_ratio', 'N/A')}
- **PE比率(预期)**: {data.get('forward_pe', 'N/A')}
- **PB比率**: {data.get('pb_ratio', 'N/A')}
- **PEG比率**: {data.get('peg_ratio', 'N/A')}
- **价格/销售额**: {data.get('price_to_sales', 'N/A')}
- **企业价值/营收**: {data.get('ev_to_revenue', 'N/A')}
- **企业价值/EBITDA**: {data.get('ev_to_ebitda', 'N/A')}

**📈 盈利能力指标**
- **净资产收益率(ROE)**: {format_percentage(data.get('roe'))}
- **总资产收益率(ROA)**: {format_percentage(data.get('roa'))}
- **净利润率**: {format_percentage(data.get('profit_margins'))}
- **毛利率**: {format_percentage(data.get('gross_margins'))}
- **营业利润率**: {format_percentage(data.get('operating_margins'))}
- **EBITDA利润率**: {format_percentage(data.get('ebitda_margins'))}

**📊 成长性指标**
- **营收增长率**: {format_percentage(data.get('revenue_growth'))}
- **净利润增长率**: {format_percentage(data.get('earnings_growth'))}
- **季度盈利增长**: {format_percentage(data.get('earnings_quarterly_growth'))}

**💳 财务健康指标**
- **股息率**: {format_percentage(data.get('dividend_yield'))}
- **股息率(年度)**: {data.get('dividend_rate', 'N/A')}
- **股息支付率**: {format_percentage(data.get('payout_ratio'))}
- **债务股权比**: {data.get('debt_to_equity', 'N/A')}
- **流动比率**: {data.get('current_ratio', 'N/A')}
- **速动比率**: {data.get('quick_ratio', 'N/A')}
- **Beta系数**: {data.get('beta', 'N/A')}

**💵 现金流指标**
- **自由现金流**: {format_currency(data.get('free_cashflow'))}
- **经营现金流**: {format_currency(data.get('operating_cashflow'))}
- **现金总额**: {format_currency(data.get('total_cash'))}
- **债务总额**: {format_currency(data.get('total_debt'))}

**📈 技术指标**
- **50日均线**: ${data.get('50_day_average', 'N/A')}
- **200日均线**: ${data.get('200_day_average', 'N/A')}
- **成交量**: {data.get('volume', 'N/A'):,}
- **平均成交量**: {data.get('average_volume', 'N/A'):,}

**🔧 技术分析指标**
- **RSI(14)**: {f"{data.get('rsi', 0):.2f}" if data.get('rsi') else 'N/A'}
- **RSI信号**: {data.get('rsi_signal', 'N/A')}
- **MACD**: {f"{data.get('macd', 0):.4f}" if data.get('macd') else 'N/A'}
- **MACD信号线**: {f"{data.get('macd_signal', 0):.4f}" if data.get('macd_signal') else 'N/A'}
- **MACD柱状图**: {f"{data.get('macd_histogram', 0):.4f}" if data.get('macd_histogram') else 'N/A'}
- **布林带上轨**: ${f"{data.get('bb_upper', 0):.2f}" if data.get('bb_upper') else 'N/A'}
- **布林带中轨**: ${f"{data.get('bb_sma', 0):.2f}" if data.get('bb_sma') else 'N/A'}
- **布林带下轨**: ${f"{data.get('bb_lower', 0):.2f}" if data.get('bb_lower') else 'N/A'}
- **布林带位置**: {f"{data.get('bb_position', 0):.1f}" if data.get('bb_position') else 'N/A'}%
- **20日波动率**: {format_percentage(data.get('volatility_20d'))}
- **趋势信号**: {data.get('trend_signal', 'N/A')}
- **1月动量**: {f"{data.get('momentum_1m', 0):.2f}" if data.get('momentum_1m') else 'N/A'}%
- **3月动量**: {f"{data.get('momentum_3m', 0):.2f}" if data.get('momentum_3m') else 'N/A'}%
- **成交量比例**: {f"{data.get('volume_ratio', 0):.2f}" if data.get('volume_ratio') else 'N/A'}x

**👨‍💼 分析师预期**
- **目标均价**: ${data.get('target_mean_price', 'N/A')}
- **目标价区间**: ${data.get('target_low_price', 'N/A')} - ${data.get('target_high_price', 'N/A')}
- **分析师评级**: {data.get('recommendation_mean', 'N/A')}/5
- **分析师数量**: {data.get('number_of_analysts', 'N/A')}位

**🏢 公司基本信息**
- **员工数量**: {data.get('full_time_employees', 'N/A'):,}
- **流通股比例**: {format_percentage(data.get('held_percent_institutions'))}
- **内部持股**: {format_percentage(data.get('held_percent_insiders'))}
- **做空比例**: {format_percentage(data.get('short_percent_of_float'))}

**🎯 用户问题**: {user_question}"""

    # 根据分析类型构建专门的提示词
    if analysis_type == 'comprehensive':
        return f"""你是一位专业的股票投资分析师。请基于以下股票信息进行全面的投资价值分析：

{stock_info}

## 分析要求
请提供以下四个方面的详细分析：

### 1. 估值分析
- 分析当前的PE、PB比率是否合理
- 与同行业平均水平对比
- 历史估值区间分析
- 给出估值水平评估

### 2. 财务健康状况
- 盈利能力分析（基于ROE等指标）
- 成长性评估
- 财务稳定性分析
- 现金流状况

### 3. 投资风险评估
- 识别主要投资风险
- 市场环境风险
- 行业特定风险
- 公司特有风险

### 4. 投资建议
- 明确的投资评级（买入/持有/卖出/观望）
- 目标价位区间（如果可能）
- 投资时间框架建议
- 仓位管理建议

请使用专业的投资分析语言，提供具体的数字和理由支撑。使用markdown格式，包含标题、列表、表格等。"""

    elif analysis_type == 'valuation':
        return f"""你是一位专业的估值分析师。请基于以下股票信息进行深入的估值分析：

{stock_info}

## 估值分析要求
请重点分析以下方面：

### 1. 相对估值分析
- **PE比率评估**：与历史5年平均值和同行业竞争对手对比
- **PB比率评估**：账面价值分析与行业平均水平对比
- **PEG比率**：增长调整后的估值评估
- **EV/EBITDA**：企业价值倍数分析

### 2. 绝对估值分析
- DCF现金流折现分析框架
- DDM股息折现模型分析

### 3. 估值结论
- 当前估值处于历史什么水平（低估/合理/高估）
- 合理估值区间是多少
- 基于估值给出的具体投资建议

请使用专业的估值分析术语，提供具体的数值对比和明确的估值结论。使用markdown格式。"""

    elif analysis_type == 'financial':
        return f"""你是一位专业的财务分析师。请基于以下股票信息进行深入的财务健康状况分析：

{stock_info}

## 财务分析要求
请提供以下详细的财务分析：

### 1. 盈利能力分析
- **毛利率**：产品竞争力和定价能力评估
- **营业利润率**：经营效率分析
- **净利润率**：最终盈利能力评估
- **ROE（净资产收益率）**：股东回报水平分析
- **ROA（总资产收益率）**：资产使用效率分析

### 2. 成长性分析
- **营收增长率**：业务扩张速度和质量
- **净利润增长率**：盈利增长可持续性
- **季度增长趋势**：增长稳定性分析

### 3. 偿债能力分析
- **流动比率/速动比率**：短期偿债能力
- **资产负债率**：财务杠杆水平评估
- **利息保障倍数**：利息支付能力

### 4. 现金流分析
- **经营性现金流**：主营业务现金创造能力
- **自由现金流**：可支配现金流状况

### 5. 财务风险评估
- 识别主要财务风险点
- 财务状况稳定性评价
- 与同行业对比分析

请使用具体的财务指标进行量化分析，给出专业的财务健康评价。使用markdown格式，可包含表格对比。"""

    elif analysis_type == 'technical':
        return f"""你是一位专业的技术分析师。请基于以下股票信息进行技术面分析：

{stock_info}

## 技术分析要求
请提供以下技术面分析：

### 1. 价格趋势分析
- **当前价格位置**：在52周区间的位置
- **趋势方向**：短期、中期、长期趋势判断
- **关键价位**：重要支撑位和阻力位分析

### 2. 移动平均线分析
- **短期均线**：MA5、MA10的位置和方向
- **中期均线**：MA20、MA60的趋势状态
- **均线排列**：多头/空头排列分析
- **均线交叉**：金叉/死叉信号识别

### 3. 技术指标分析
- **RSI相对强弱指数**：当前数值和超买超卖状态
- **MACD指标**：快慢线位置和方向
- **其他重要指标**：KDJ、布林带等

### 4. 成交量分析
- **成交量变化趋势**：放量/缩量分析
- **量价关系**：价涨量增/价跌量增等模式

### 5. 短期技术信号
- **买入/卖出信号**：基于技术指标
- **风险控制点**：止损/止盈位置建议
- **时间窗口**：短期走势预测（1-4周）

请使用技术分析的专业术语，给出具体的技术信号和操作建议。使用markdown格式。"""

    elif analysis_type == 'risk':
        return f"""你是一位专业的风险管理分析师。请基于以下股票信息进行全面的投资风险评估：

{stock_info}

## 风险评估要求
请系统性地分析以下风险因素：

### 1. 系统性风险
- **市场风险**：整体市场波动对股价的影响
- **行业风险**：行业周期性、政策变化风险
- **宏观经济风险**：利率、汇率、经济增长等影响

### 2. 非系统性风险
- **公司经营风险**：管理层变动、技术/产品、供应链、客户集中度风险
- **财务风险**：流动性、债务违约、汇率风险
- **估值风险**：估值泡沫、市场情绪逆转风险

### 3. 特有风险因素
- **监管风险**：政策监管变化
- **竞争风险**：行业竞争加剧
- **技术风险**：技术迭代更新风险

### 4. 风险等级评估
- **低风险因素**：相对可控的风险
- **中风险因素**：需要关注的风险
- **高风险因素**：需要重点监控的风险

### 5. 风险控制建议
- 仓位控制建议
- 止损设置建议
- 分散投资建议
- 持续监控要点

请按风险等级进行分类，给出具体的风险管理建议。使用markdown格式。"""

    elif analysis_type == 'outlook':
        return f"""你是一位专业的投资策略师。请基于以下股票信息进行发展前景和长期投资价值分析：

{stock_info}

## 前景展望要求
请提供以下前景分析：

### 1. 行业前景分析
- **行业发展趋势**：未来3-5年行业发展方向
- **市场规模预测**：行业增长空间和潜力
- **技术创新趋势**：技术革新对行业的影响
- **政策环境影响**：相关政策对行业的支撑或限制

### 2. 公司竞争优势
- **核心护城河**：品牌、技术、网络效应等竞争优势
- **市场地位**：在行业中的排名和影响力
- **研发能力**：创新投入和技术储备
- **管理团队**：管理层能力和战略执行力

### 3. 成长驱动因素
- **现有业务增长**：市场份额提升、产品升级
- **新业务拓展**：新兴市场和新产品线
- **并购整合**：外延式增长机会
- **国际化机会**：海外市场拓展潜力

### 4. 财务前景预测
- **营收增长预测**：未来3年营收增长预期
- **利润增长预测**：盈利能力提升预期
- **现金流预测**：现金生成能力展望

### 5. 长期投资价值
- **投资逻辑**：长期投资的核心逻辑
- **目标价位**：基于基本面的合理目标价
- **投资时间框架**：建议的持有期限
- **潜在催化剂**：可能推动股价上涨的催化剂

### 6. 发展不确定性
- **主要挑战**：面临的主要困难
- **关键假设**：前景预测基于的关键假设
- **风险提示**：需要持续关注的风险点

请提供具体的数据支撑和清晰的投资逻辑，给出有说服力的长期投资建议。使用markdown格式。"""

    else:
        # 默认综合分析
        return f"""请基于以下股票信息进行投资分析：

{stock_info}

请提供专业的投资分析建议，使用markdown格式。"""


if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=True)
